<template>
  <div>
    <Header />
    <div class="block">
      <el-timeline>
        <el-timeline-item
          v-for="post in posts"
          :key="post.postId"
          :timestamp="post.creatTime"
          placement="top"
        >
          <el-card>
            <router-link
              :to="{ name: 'PostDetail', params: { postId: post.postId } }"
            >
              <h4>{{ post.title }}</h4>
            </router-link>
            <p>{{ post.content }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>
    <el-pagination
      class="mpage"
      background
      layout="prev, pager, next"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @current-change="page"
    />
  </div>
</template>

<script>
import { postList, deletePost } from '@/api/post'
export default {
  name: 'Posts',
  data() {
    return {
      posts: {}, // 修改为数组形式
      currentPage: 1,
      total: 0,
      pageSize: 4
    }
  },
  mounted() {
    this.page(1)
  },
  methods: {
    async page(currentPage) {
      const response = await postList(currentPage)
      this.posts = response.data.records
      this.currentPage = response.data.current
      this.total = response.data.total
      this.pageSize = response.data.size
    },
    async deletePost(postId) {
      try {
        const response = await deletePost(postId)
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          // 删除成功后刷新页面或重新请求数据
          this.page(this.currentPage)
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        console.error('删除失败', error)
      }
    }
  }
}
</script>

<style scoped>
.mpage {
  margin: 0 auto;
  text-align: center;
}
</style>
